package com.qf.blog.controller;

import com.qf.blog.entity.Comment;
import com.qf.blog.entity.User;
import com.qf.blog.exception.BlogException;
import com.qf.blog.service.ICommentService;
import com.qf.blog.service.impl.PostScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 达哥
 * @since 2023-03-25
 */
@Controller
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private ICommentService commentService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PostScoreService postScoreService;

    @PostMapping("/create")
    public String create(Comment comment, HttpSession session) {

        // 1.先判断用户是否登录
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            throw new BlogException(1004, "请先登录!");
        }

        // 2.封装数据
        comment.setStatus(1);
        comment.setUserId(loginUser.getId()); // 当前登录用户ID
        comment.setCreateTime(new Date());
        // 下面的属性值全部从页面来
//        comment.setTargetId(null); // 帖子的作者
//        comment.setEntityType(null); // 实体类
//        comment.setContent(null); // 用户在表单填写
//        comment.setEntityId(null); // 实体的ID

        // 3.入库
        commentService.save(comment);

        // 帖子的评论数量发送了改变，需要把帖子id写入到redis中重新计算帖子分数
        postScoreService.addPostToRedis(comment.getEntityId());


        // 4.继续重定向到当前帖子的详情页面
        return "redirect:/post/info/"+comment.getEntityId();
    }

}
